import React, {useCallback, useEffect, useState} from "react";
import MessageShow from "@/components/Summary/MessageShow.jsx";
import SummaryShow from "@/components/Summary/SummaryShow.jsx";
import {useLocation, useNavigate} from "react-router-dom";
import {getChat} from "@/apis/chat.js";
import {analyseSummarize, downloadReportDocx} from "@/apis/analyzer.js";
import {Layout, Spin} from "antd";
import {SummaryInfoPanel} from "@/components/Summary/SummaryInfoPanel.jsx";
import "./Common.css";

export function SummaryPage() {
  const location = useLocation();
  const navigate = useNavigate();

  const chatId = location.state?.chatId;
  const [messages, setMessages] = useState([]);
  const [summary, setSummary] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      if (!chatId) return;
      try {
        const chatRes = await getChat(chatId);
        setMessages(chatRes.messages || []);
        const summaryRes = await analyseSummarize(chatId);
        setSummary(summaryRes);
      } catch (e) {
        console.error("获取数据失败", e);
      }
      setLoading(false);
    }

    void fetchData();
    setLoading(false);
  }, [chatId]);

  const onDownLoad = useCallback(
    async function () {
      if (loading) {
        console.log("正在加载数据，请稍后再试。");
      } else {
        console.log("下载数据");
        try {
          // 调用下载函数
          await downloadReportDocx(chatId);
        } catch (error) {
          console.error("下载失败:", error);
        }
      }
    },
    [loading, chatId]
  );

  function onClose() {
    navigate("/");
  }

  return (
    <Layout className="layoutRoot">
      <Layout.Content className="contentBox">
        <SummaryInfoPanel onDownLoad={onDownLoad} onClose={onClose}/>
        {loading ? (
          <Spin tip="加载中..." style={{margin: "48px auto"}}/>
        ) : (
          <>
            <MessageShow messages={messages}/>
            <div style={{height: 16}}/>
            <SummaryShow summary={summary || {}}/>
          </>
        )}
      </Layout.Content>
    </Layout>
  );
}

export default SummaryPage;
